package cn.itcast.aisi.controller;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itcast.aisi.dto.AiSiOrder;
import cn.itcast.aisi.dto.IpTablesDto;
import cn.itcast.controller.IpBean;
import cn.itcast.aisi.dto.AiSiGoodsList;
import cn.itcast.utils.AESUtils;
import cn.itcast.utils.DingDingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.*;

/**
 * 艾斯
 */
@RestController
@Slf4j
public class AiSiController {
    private static List<IpBean> list=new ArrayList<>();
    private static List<String> tokenList=new ArrayList<>();
    public  static Map<String,IpBean> ret=new HashMap<>();
    @RequestMapping("/createAsMarket")
    public String createAsMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(CollectionUtils.isEmpty(list)){
            try{
                IpBean ipBean1 = new IpBean();
                ipBean1.setIpAddress("117.160.250.132");
                ipBean1.setPort(8080);
                list.add(ipBean1);
            }catch (Exception e){
                IpBean ipBean=new IpBean();
                list.add(ipBean);
            }
        }
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                for(int j=0;j<list.size();j++){
                    for(int z=0;z<tokenList.size();z++){
                        IpBean ipBean=list.get(j);
                        String ips=null;
                        IpBean bean=null;
                        if(ret.containsKey("ip")){
                            bean=  ret.get("ip");
                            if(bean.getDate()<(new Date().getTime())){
                                ips=HttpRequest.get("http://tiqu.pyhttp.taolop.com/getflowip?count=1&neek=70500&type=1&sep=1&sb=&ip_si=1&mr=0")
                                        .execute().body();
                                bean.setIpAddress(ips);
                                bean.setDate(new Date().getTime()+2000);
                            }else{
                                ips=bean.getIpAddress();
                            }
                        }else{
                            bean=new IpBean();
                            ips=HttpRequest.get("http://tiqu.pyhttp.taolop.com/getflowip?count=1&neek=70500&type=1&sep=1&sb=&ip_si=1&mr=0")
                                    .execute().body();
                            bean.setIpAddress(ips);
                            bean.setDate(new Date().getTime()+2000);
                        }
                        ret.put("ip",ipBean);
                        log.info("######请求ip返回数据####："+ips.trim());
                        String str[]=ips.trim().split(":");
                        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(str[0], Integer.parseInt(str[1])));
                        confireMarketOrder(proxy,tokenList.get(z),goodsId,salePrice);
                        Thread.sleep(1000);
                    }

                }
            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####热浪执行完成#####");
        return null;
    }
    public void confireMarketOrder(Proxy proxy,String token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####创建订单失败####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,String token,String goodsId,String salePrice) throws InterruptedException {
        String response=null;
        JSONObject requestJson=new JSONObject();
        requestJson.putOnce("page",1);
        requestJson.putOnce("limit",10);
        //requestJson.putOnce("collection_id",469);
        requestJson.putOnce("collection_id",goodsId);
        requestJson.putOnce("type_field",2);
        requestJson.putOnce("phone_number","13803993919");
        requestJson.putOnce("token","");
        requestJson.putOnce("sign_time",new Date().getTime());
        String result=null;
        try{
            String data= URLEncoder.encode(AESUtils.encrypt(requestJson.toString()),"utf-8");
            result = HttpRequest.get("https://xin.iswenchuang.cn/api/market/newpackorderlistdetail?data="+data)
                    .header("authorization",token)
                    .setProxy(proxy)
                    .setReadTimeout(5000)
                    .execute().body();
            response=AESUtils.deciphering(result);
        }catch (Exception e){
            log.info("####请求商品数据异常######"+e.getMessage()+"####"+result);
        }
        if(!StringUtils.isEmpty(response)){
            AiSiGoodsList
                    siGoodsList= JSONUtil.toBean(response, AiSiGoodsList.class);
            log.info("######获取商品数据成功#######"+siGoodsList.toString());
            if(siGoodsList.getData()!=null && !CollectionUtils.isEmpty(siGoodsList.getData().getData())){
                List<AiSiGoodsList.AiSiGoodsDetailList> list=siGoodsList.getData().getData();
                for(AiSiGoodsList.AiSiGoodsDetailList detailDTO:list){
                    if(new BigDecimal(detailDTO.getPayPrice()).compareTo(new BigDecimal(salePrice))<=0){
                        Proxy finalProxy = proxy;
                        ThreadUtil.execAsync(() -> {
                            saveOrder(finalProxy,token,detailDTO);
                        });
                        Thread.sleep(1100);
                    }

                }
            }
        }else{
            log.info("##获取商品数据异常##");
        }
    }

    public void saveOrder(Proxy proxy,String token,AiSiGoodsList.AiSiGoodsDetailList detailDTO){
        JSONObject dataId=new JSONObject();
        dataId.putOnce("id",detailDTO.getId());
        String dataJson=dataId.toString();
        String entry=AESUtils.encrypt(dataJson);
        String id=entry.replaceAll("/+","%7C").
                replaceAll("%3b","/").replaceAll("=","~");
        JSONObject createJson = new JSONObject();
        createJson.putOnce("returnurl", "https://h5.iswenchuang.cn/#/pages/market/detail_old?id="+id+"&order_sn=");
        createJson.putOnce("id", detailDTO.getId());
        createJson.putOnce("pay_type1",detailDTO.getPayType1());
        createJson.putOnce("pay_type2",detailDTO.getPayType2());
        createJson.putOnce("pay_type3",detailDTO.getPayType3());
        createJson.putOnce("sign_time",new Date().getTime());
        createJson.putOnce("pay_type",4);
        String data= null;
        String createResult=null;
        AiSiOrder aiSiOrder=null;
        try {
            data = URLEncoder.encode(AESUtils.encrypt(createJson.toString()),"utf-8");
            createResult = HttpRequest.post("https://xin.iswenchuang.cn/api/order/newbuymarket?data="+data)
                    .header("authorization",token)
                    .setProxy(proxy)
                    .execute().body();
            createResult=AESUtils.deciphering(createResult);
            aiSiOrder= JSONUtil.toBean(createResult, AiSiOrder.class);
            log.info("####支付结果######"+aiSiOrder.toString());
        } catch (Exception e) {
            log.info("####支付结果异常######"+e.getMessage()+":detailDTO"+detailDTO.toString());
        }
        if(null!=aiSiOrder && aiSiOrder.getAiSiOrderDetail()!=null){
            //请求数据生成url连接
            log.error("####生成订单数据######"+aiSiOrder.getAiSiOrderDetail().getUrl());
            DingDingUtils.sendMsg("艾斯您有一个新的订单，请赶紧支付");
        }
    }
    public void addToken(){
        tokenList.add("Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wveGluLmlzd2VuY2h1YW5nLmNuXC9hcGlcL2xvZ2luXC9pbmRleCIsImlhdCI6MTY4MTA5NTMwNiwiZXhwIjoxODM2NjE1MzA2LCJuYmYiOjE2ODEwOTUzMDYsImp0aSI6Im5OYWFmMjBjS3A4UjhINEkiLCJzdWIiOjEwNzkyMywicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9.8rn6V26RsUBn1Nd842uOVmksyHJsvRlQ4miuhwX8c0c");
    }

}
